<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <!--<a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :span="6">
            <a-form-item label="名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入材料名称" v-model="queryParam.materialName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="型号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入型号" v-model="queryParam.modelNumber"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="规格" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入规格" v-model="queryParam.specifications"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="供应商" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select
                show-search
                :allowClear="true"
                placeholder="请选择供应商"
                option-filter-prop="children"
                v-model="queryParam.supplierId"
                style="width: 100%"
                :filter-option="filterOptionSupplier"
                @change="changeSupplier">
                <a-select-option :value="item.id" v-for="(item,index) in supplierData" :key="index">
                  {{item.supplierName}}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :span="6">
            <a-form-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select v-model="queryParam.status" placeholder="请选择状态" @change="changeMaterialType" :allowClear="true">
                <a-select-option value="1">启用</a-select-option>
                <a-select-option value="2">停用</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="品牌" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入品牌" v-model="queryParam.brand"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="材料编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入材料编号" v-model="queryParam.materialSerial"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6" >
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>-->
    </div>
    <!-- 查询区域-END -->
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <!--<a-button @click="addMaterial" type="primary" icon="plus">新增</a-button>-->
      <!--<a-button type="primary" icon="download" @click="handleExportXls('材料管理表')">导出</a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="importExcel">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>
      <a-button type="primary" icon="download" @click="downloadMould('materialInfo_mould')">下载导入模板</a-button>-->
      <!-- 高级查询区域 -->
      <!--<j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>-->
      <!--<a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
          <a-menu-item key="2" @click="batchUpdate"><a-icon type="edit"/>修改</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>-->
    </div>
    <!-- table区域-begin -->
    <div>
      <!--<div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>-->

      <div class="list">
        <van-list
          v-model="loading"
          :finished="finished"
          offset="100"
          finished-text="没有更多了"
          @load="onLoadList"
          :immediate-check="false"
        >
          <div
            class="customer-list"
            v-for="(item,i) in dataSource"
            :key="i"
            @click="materialDetail(item)"
          >
            <div>
              <div class="name">材料名称：{{ item.materialName || '无' }}</div>
              <div class="contact">
                <span>型号：{{ item.modelNumber || '无' }}</span>
              </div>
              <div class="contact">
                <span>规格：{{ item.specifications || '无' }}</span>
              </div>
              <div class="contact">
                <span>品牌：{{ item.brand || '无' }}</span>
              </div>
              <div class="contact">
                <span>供应商：{{ item.ghSupplychainSupplier.supplierName || '无' }}</span>
              </div>
              <div class="contact">
                <span>状态：
                  <a-tag color="green" v-if="item.status === 1">启用</a-tag>
                  <a-tag color="orange" v-if="item.status === 2">禁用</a-tag>
                </span>
              </div>
              <div class="contact">
                <span>材料类型：{{ item.materialTypeName || '无' }}</span>
              </div>
              <div class="contact">
                <span>市场价：{{ item.marketPrice || '无' }}</span>
                <span style="margin-left: 20px;margin-right: 20px">预算价：{{ item.estimatedCost || '无' }}</span>
                <span>成本价：{{ item.costPrice || '无' }}</span>
              </div>
            </div>
          </div>
        </van-list>
      </div>

      <!--<a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :scroll="{x:true}"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :customRow="setRow"
        :rowSelection="{
          selectedRowKeys: selectedRowKeys,
          onSelectAll:onSelectAll,
          onSelect:onSelect,
          onChange: onSelectChange,
          type:'checkbox'
        }"
        @change="handleTableChange"
        class="j-table-force-nowrap">
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text,record">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" :preview="record.id" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="materialDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

      </a-table>-->
    </div>
    <a-modal v-model="showErrorDate" :footer="null" width="80%" title="导入失败数据">
      <a-table
        :scroll="{x:true}"
        :columns="errorColumns"
        :data-source="errorData"
        :pagination="ipaginationError"
        :loading="loading"
        class="j-table-force-nowrap"
      >
      </a-table>
    </a-modal>
    <gh-supplychain-material-modal ref="modalForm" @ok="modalFormOk"></gh-supplychain-material-modal>
    <material-detail-modal ref="materialDetailModal"></material-detail-modal>
    <update-batch-modal ref="updateBatchModal" @ok="modalFormOk"></update-batch-modal>
  </a-card>
</template>

<script>
  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import GhSupplychainMaterialModal from './modules/GhSupplychainMaterialModal'
  import materialDetailModal from "./modules/materialDetailModal";
  import { getAction, putAction } from '../../../../api/manage'
  import Vue from "vue";
  import updateBatchModal from './modules/updateBatchModal'

  export default {
    name: 'materialList',
    mixins:[JeecgListMixin, mixinDevice],
    components: {
      GhSupplychainMaterialModal,materialDetailModal,updateBatchModal,
    },
    data () {
      return {
        description: '材料管理表管理页面',
        obj: {},
        errorData: [],
        dataSource: [],
        ipagination: {},
        loading: false,
        ipaginationError: {},
        showErrorDate: false,
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'材料编号',
            align:"center",
            dataIndex: 'materialSerial'
          },
          {
            title:'名称',
            align:"center",
            dataIndex: 'materialName'
          },
          {
            title:'型号',
            align:"center",
            dataIndex: 'modelNumber'
          },
          {
            title:'规格',
            align:"center",
            dataIndex: 'specifications'
          },
          {
            title:'品牌',
            align:"center",
            dataIndex: 'brand'
          },
          {
            title:'单位',
            align:"center",
            dataIndex: 'unit'
          },
          {
            title:'材料类型',
            align:"center",
            dataIndex: 'materialTypeName'
          },
          {
            title:'供应商',
            align:"center",
            dataIndex: 'ghSupplychainSupplier.supplierName'
          },
          {
            title:'材料状态',
            align:"center",
            dataIndex: 'status',
            customRender:function (text) {
              return text == 1 ? <a-tag color="green">启用</a-tag> : <a-tag color="orange">禁用</a-tag>
            }
          },
          {
            title:'市场价/元',
            align:"center",
            dataIndex: 'marketPrice',
            customRender:function (text) {
              if (text == "" || text == null){
                return "-"
              }else {
                return text
              }
            }
          },
          {
            title:'预算价/(元)',
            align:"center",
            dataIndex: 'estimatedCost',
            customRender:function (text) {
              if (text == "" || text == null){
                return "-"
              } else {
                return text
              }
            }
          },
          {
            title:'成本价/元',
            align:"center",
            dataIndex: 'costPrice',
            customRender:function (text) {
              if (text == "" || text == null){
                return "-"
              } else {
                return text
              }
            }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: "center",
            fixed: "right",
            width: 147,
            scopedSlots: {customRender: 'action'}
          }
        ],
        errorColumns: [
          {
            title:'材料编号',
            align:"center",
            dataIndex: 'materialSerial'
          },
          {
            title:'名称',
            align:"center",
            dataIndex: 'materialName'
          },
          {
            title:'材料类型',
            align:"center",
            dataIndex: 'materialTypeName'
          },
          {
            title:'供应商',
            align:"center",
            dataIndex: 'supplierName'
          },
          {
            title:'型号',
            align:"center",
            dataIndex: 'modelNumber'
          },
          {
            title:'规格',
            align:"center",
            dataIndex: 'specifications'
          },
          {
            title:'品牌',
            align:"center",
            dataIndex: 'brand'
          },
          {
            title:'市场价/元',
            align:"center",
            dataIndex: 'marketPrice',
            customRender:function (text) {
              if (text == "" || text == null){
                return "-"
              }else {
                return text
              }
            }
          },
          {
            title:'预算价/元',
            align:"center",
            dataIndex: 'estimatedCost',
            customRender:function (text) {
              if (text == "" || text == null){
                return "-"
              } else {
                return text
              }
            }
          },
          {
            title:'成本价/元',
            align:"center",
            dataIndex: 'costPrice',
            customRender:function (text) {
              if (text == "" || text == null){
                return "-"
              } else {
                return text
              }
            }
          },{
            title:'原因',
            align:"center",
            dataIndex: 'errorMessage',
            customCell: () => {
              return {
                style: {
                  color: 'red'
                }
              }
            }
          }
        ],
        url: {
          list: "/ghSupplychainMaterial/list",
          delete: "/ghSupplychainMaterial/delete",
          deleteBatch: "/ghSupplychainMaterial/deleteBatch",
          exportXlsUrl: "/ghSupplychainMaterial/exportXls",
          importExcelUrl: "/ghSupplychainMaterial/importExcel",
          supplierList: "/ghSupplychainSupplier/allList",
          queryMouldByCode: "/ghImportMould/queryByCode",
        },
        labelCol: { xs: { span: 24 }, sm: { span: 5 } },
        wrapperCol: { xs: { span: 24 },  sm: { span: 16 } },
        dictOptions:{},
        superFieldList:[],
        supplierData:[],
        selectedRowKeys: [],
        selectedRows: [],
        finished: false,
      }
    },
    created() {
      this.loadData();
      this.loadSupplierData();
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      onLoadList(e){
        this.ipagination.current++
        this.loadData(this.ipagination.current)
      },
      loadData(arg) {
        this.loading = true;
        if (!this.url.list) {
          this.$message.error("请设置url.list属性!")
          return;
        }
        if (arg === 1) {
          this.ipagination.current = 1;
          this.dataSource = []
          this.finished = false;
        }
        let params = this.getQueryParams();//查询条件
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            this.dataSource = [...this.dataSource, ...res.result.records]
            this.ipagination.total = res.result.total
          } else {
            this.$message.warning(res.message)
          }
          if(res.result.records.length<10){
            this.finished = true;
          }
        }).finally(() => {
          this.loading = false
        })
      },
      handleTableChange(pagination) {
        this.ipagination = pagination;
        this.loadData();
      },
      addMaterial(){
        this.$refs.modalForm.title = "添加"
        this.$refs.modalForm.add();
      },
      changeSupplier(){
        this.loadData(1);
      },
      loadSupplierData(){
        getAction(this.url.supplierList).then((res) => {
          if (res.success) {
            this.supplierData = res.result.records||res.result;
          }else{
            this.$message.warning(res.message)
          }
        })
      },
      materialDetail(record){
        this.$refs.materialDetailModal.showDrawer(record);
        this.$refs.materialDetailModal.title = "材料详情"
      },
      changeMaterialType(value){
        this.loadData(1);
      },
      //下载模板
      downloadMould(value){
        getAction(this.url.queryMouldByCode,{code: value})
          .then(res => {
            if (res.success) {
              this.obj = res.result;
              window.location = this.obj.mouldUrl+'?response-content-type=application/octet-stream';
            }
        })
      },
      importExcel(info){
        this.loading = true;
        if (info.file.status !== 'uploading') {
        }

        if (info.file.status === 'done') {
          this.loading = false;
          if (info.file.response.success) {
            if (info.file.response.result != null) {
              let { result } = info.file.response
              if(result.length > 0) {
                this.showErrorDate = true;
                this.errorData = result;
              } else {
                this.$message.success(info.file.response.message || `${info.file.name} 文件上传成功`)
              }
            } else {
              this.$message.success(info.file.response.message || `${info.file.name} 文件上传成功`)
            }
            this.loadData()
          } else {
            this.$message.error(`${info.file.name} ${info.file.response.message}.`);
          }
        } else if (info.file.status === 'error') {
          this.loading = false;
          if (info.file.response.status === 500) {
            let data = info.file.response
            const token = Vue.ls.get(ACCESS_TOKEN)
            if (token && data.message.includes("Token失效")) {
              this.$error({
                title: '登录已过期',
                content: '很抱歉，登录已过期，请重新登录',
                okText: '重新登录',
                mask: false,
                onOk: () => {
                  store.dispatch('Logout').then(() => {
                    Vue.ls.remove(ACCESS_TOKEN)
                    window.location.reload();
                  })
                }
              })
            }
          } else {
            this.$message.error(`文件上传失败: ${info.file.msg} `);
          }
        }
      },
      filterOptionSupplier(input, option){
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      onSelectAll(selected, selectedRows, changeRows) {
        if(selected) {
          let rows = [...selectedRows]
          this.selectedRows = this.selectedRows.concat(rows)
        } else {
          changeRows.forEach(item => {
            const delIndex = this.selectedRows.findIndex((val) => {
              return val.id === item.id
            })
            this.selectedRows.splice(delIndex, 1)
          })
        }
      },
      onSelect(record, selected) {
        if(selected) {
          this.selectedRows.push(record);
        } else {
          const delIndex = this.selectedRows.findIndex((val) => {
            return val.id === record.id
          })
          this.selectedRows.splice(delIndex,1)
        }
      },
      onSelectChange(selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys;
      },
      //批量修改
      batchUpdate(){
        let ids = "";
        for (let a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ",";
        }
        this.$refs.updateBatchModal.add(ids);
      },
    }
  }
</script>
<style scoped lang="less">
  @import '~@assets/less/common.less';

  .remarkTxt{
    max-width: 350px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  /deep/ .van-dropdown-menu__bar{
    height: 30px;
    box-shadow: none;
    border: 1px solid lightgrey;
    border-radius: 5px;
  }

  .list{
    overflow-y: scroll;
    height:calc(100vh - 155px);
  }
  ::-webkit-scrollbar {
    display: none;
  }
  .customer-list {
    align-items: center;
    border-top: 1px solid #d9d9d9;
    /*height: 120px;*/
  }
  .name{
    margin-top: 10px;
    margin-bottom: 5px;
    font-size: 13px;
    color: #161616;
    line-height: normal;
  }
  .contact{
    font-size: 12px;
    color: #a39f9f;
    margin-bottom: 5px;
  }
</style>